#pragma once

#include <iostream>
#include <string>
#include <strings.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include "Log.hpp"
#include <unordered_map>

typedef std::function<std::string(const std::string &)> func_t;

Log lg;

enum
{
    SOCKET_ERR = 1,
    BIND_ERR
};

uint16_t defaultport = 8080;
std::string defaultip = "0.0.0.0";
const int size = 1024;

class UdpServer
{
public:
    UdpServer(const uint16_t &port = defaultport, std::string ip = defaultip)
        : sockfd_(0), ip_(ip), port_(port), isrunning_(false)
    {
    }

    // 当以下三步完成后，你的服务端已经可以接待顾客了。也就是说，它已经准备好接收来自客户端的请求。
    void Init()
    {
        // 1.创建socket  AF_INET  ipv4   SOCK_DGRAM   udp
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd_ < 0)
        {
            lg(Fatal, "socket create error, sockfd: %d", sockfd_);
            exit(SOCKET_ERR);
        }
        lg(Info, "socket create success, sockfd: %d", sockfd_);

        // 2. 创建结构体来传入你服务端的数据信息
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        // 传入ipv4
        local.sin_family = AF_INET;
        // 穿端口
        local.sin_port = htons(port_); // htons():将本机字节序的端口号转换为网络字节序（大端字节序）。
        // 传入IP地址
        local.sin_addr.s_addr = INADDR_ANY;

        // 3.将结构体中的信息绑定到socket
        if (bind(sockfd_, (const sockaddr *)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind error, errno: %d, err string: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        lg(Info, "bind success, errno: %d, err string: %s", errno, strerror(errno));
    }

    void CheckUser(const struct sockaddr_in &client, const std::string clientip, uint16_t clientport)
    {
        auto iter = online_user_.find(clientip);
        if (iter == online_user_.end()) // 没找到
        {
            // 添加客户
            online_user_.insert({clientip, client});
            std::cout << "[" << clientip << ":" << clientport << "] add to online user." << std::endl;
        }
    }
    void Broadcast(const std::string &info, const std::string clientip, uint16_t clientport)
    {
        //[192.168.1.1:8080]# Hello, world!
        for (const auto &user : online_user_)
        {
            std::string message = "[";
            message += clientip;
            message += ":";
            message += std::to_string(clientport);
            message += "]# ";
            message += info;
            std::cout<<message<<std::endl;
            // 将message发送给所有的用户
            socklen_t len = sizeof(user.second);
            sendto(sockfd_,message.c_str(),message.size(),0,(struct sockaddr*)(&user.second),len);
        }
    }
    void Run() // 对代码进行分层
    {
        isrunning_ = true;
        char inbuffer[size];
        while (isrunning_)
        {
            // 获取客户端信息
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(sockfd_, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&client, &len);
            if (n < 0)
            {
                lg(Warning, "recvfrom error, errno: %d, err string: %s", errno, strerror(errno));
                continue;
            }

            uint16_t clientport = ntohs(client.sin_port); // 网络->客户
            std::string clientip = inet_ntoa(client.sin_addr);
            CheckUser(client, clientip, clientport);

            std::string info = inbuffer; // 收到的信息
            Broadcast(info, clientip, clientport);
        }
    }

    // void Run(func_t func) // 对代码进行分层
    // {
    //     isrunning_ = true;
    //     char inbuffer[size];
    //     while(isrunning_)
    //     {
    //         struct sockaddr_in client;
    //         socklen_t len = sizeof(client);
    //         ssize_t n = recvfrom(sockfd_, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr*)&client, &len);
    //         if(n < 0)
    //         {
    //             lg(Warning, "recvfrom error, errno: %d, err string: %s", errno, strerror(errno));
    //             continue;
    //         }
    //         inbuffer[n] = 0;
    //         std::string info = inbuffer;

    //         lg(Info, "Received from client: %s", info.c_str());

    //         std::string echo_string = func(info);
    //         sendto(sockfd_, echo_string.c_str(), echo_string.size(), 0, (const sockaddr*)&client, sizeof(struct sockaddr_in));
    //     }
    // }
    ~UdpServer()
    {
        if(sockfd_>0) close(sockfd_);
    }
private:
    int sockfd_; // 网络文件描述符
    std::string ip_;
    uint16_t port_;
    bool isrunning_;

    std::unordered_map<std::string, struct sockaddr_in> online_user_; // 添加键值匹配
};